package com.cspm.ahjy.bc.office.word.util;

import org.json.JSONObject;
import org.springframework.util.StringUtils;

import com.cspm.ahjy.bc.office.word.domain.MSActionType;
import com.cspm.ahjy.bc.office.word.domain.MSTableAction;

/**
 * 表格的原子操作工具类
 * @author ServerZhang
 * @date 2017年10月12日
 */
public class TableActionUtil {
	
	/**
	 * 解析json为MSTableAction对象
	 * @param jsonStr
	 * @return
	 * @author ServerZhang
	 * @date 2017年10月24日
	 */
	public static MSTableAction getMSTableAction4Json(String jsonStr){
		MSTableAction tableAction = new MSTableAction();
		
		Boolean canDo = true;
		// 检查字符串是否合法
		canDo = jsonStr.startsWith("{") && jsonStr.endsWith("}");
		if (!canDo) {
			return null;
		}

		JSONObject jsonObject = new JSONObject(jsonStr);
		
		Object actionPreObj = jsonObject.get("actionPre");
		if (actionPreObj != null) {
			tableAction.setActionPre(actionPreObj.toString());
		}
		Object insertObj = jsonObject.get("insert");
		if (insertObj != null) {
			tableAction.setInsert(Boolean.parseBoolean(insertObj.toString()));
		}
		Object tableNoObj = jsonObject.get("tableNo");
		if (tableNoObj != null) {
			tableAction.setTableNo(Integer.parseInt(tableNoObj.toString()));
		}
		Object msActionTypeObj = jsonObject.get("msActionType");
		if (!StringUtils.isEmpty(msActionTypeObj)) {
			tableAction.setMsActionType(ActionTypeUtil.getMsActionType4Json(msActionTypeObj.toString()));
		}
		
		return tableAction;
	}
	
	public static void printAction(MSTableAction tableAction){
		String actionPre = tableAction.getActionPre();
		MSActionType msActionType = tableAction.getMsActionType();
		if (actionPre == null || msActionType == null) {
			return;
		}
		System.out.println(actionPre+"："+msActionType.getTypeContent());
	}
	
	/**
	 * 装饰Word的一个操作，对其生成操作前缀
	 * @param msTableAction
	 * @return
	 * @author ServerZhang
	 * @date 2017年10月19日
	 */
	public static MSTableAction dekorateAction(MSTableAction msTableAction){
		MSTableAction tableAction = msTableAction;
		MSActionType msActionType = msTableAction.getMsActionType();
		
		if (msActionType == null) {
			return tableAction;
		}
		
		Integer tableNo = msTableAction.getTableNo();
		//String typeContent = msActionType.getTypeContent();
		
		StringBuffer inforBuffer = new StringBuffer();
		
		if (tableNo == null || tableNo.equals(0)) {
			inforBuffer.append("设置表格");
		}else {
			inforBuffer.append("设置第 ").append(tableNo).append(" 个表格");
		}
		tableAction.setActionPre(inforBuffer.toString());
		
		return tableAction;
	}
	
}
